﻿#ifndef WRSTATEDISPLAY
#define WRSTATEDISPLAY

#include <QMutex>
#include <QWidget>
#include <QCoreApplication>
#include "../WRSoft-Utility/Framing/WRStateHandler.h"
#include "WRStateDisplayEvent.h"

//表示状态显示。
template <class T> class WRStateDisplay : public WRStateHandler
{
private:
    QMutex m_mutex;
    QWidget* m_owner;
    T m_currValue;
    T m_showValue;
    int m_currVersion;
    int m_showVersion;
    bool m_updating;

public:
    //获取所有者。
    inline QWidget* owner(void) const
    {
        return m_owner;
    }
    //设置所有者。
    inline void owner(QWidget* value)
    {
        m_owner = value;
    }

    //获取当前值。
    inline const T& value(void) const
    {
        return m_showValue;
    }
    //获取当前版本。
    inline int version(void) const
    {
        return m_showVersion;
    }

    //改变状态值。
    inline void change(const T& value)
    {
        QMutexLocker lck(&m_mutex);

        m_currValue = value;
        ++m_currVersion;
        if (!m_updating)
        {
            m_updating = true;
            QCoreApplication::postEvent(m_owner, new WRStateDisplayEvent(this));
        }
    }

    //应用改变。
    inline bool applyChanges()
    {
        QMutexLocker lck(&m_mutex);

        if (m_currVersion != m_showVersion)
        {
            m_showValue = m_currValue;
            m_showVersion = m_currVersion;
            m_updating = false;
            return true;
        }
        return false;
    }

    //初始化状态显示。
    inline explicit WRStateDisplay(QWidget* owner = 0)
    {
        m_owner = owner;
        m_currVersion = 0;
        m_showVersion = 0;
        m_updating = false;
    }
    //初始化状态显示。
    inline WRStateDisplay(QWidget* owner, const T& defValue)
        : m_showValue(defValue)
    {
        m_owner = owner;
        m_currVersion = 0;
        m_showVersion = 0;
        m_updating = false;
    }

    //当状态改变后调用此方法。
    void doProcess(const void* value)
    {
        change(*(const T*)value);
    }
};

#endif // WRSTATEDISPLAY

